package com.example.demo.service.impl;

import ch.qos.logback.core.util.FileUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.druid.util.StringUtils;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Result;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.JWTUtil;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.StringUtil;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${download.path}")
    private String filePaths;
    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;
    @Override
    public List<Map<String,Object>> getInterId(Map<String, Object> params) {
        return userMapper.getInterId(params);
    }

    @Transactional
    @Override
    public Result register(MultipartFile[] file, Map<String, Object> map, HttpServletRequest request) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> paramMap= (Map<String, Object>) JSONUtils.parse(map.get("paramMap").toString());
        //返回图片保存地址
        String img=null;
        if(file!=null&&file.length>0){
            img= file[0].getOriginalFilename();
        }
        if(Objects.isNull(paramMap.get("password"))){
            paramMap.put("password",bCryptPasswordEncoder.encode("1234"));
        }else{
            paramMap.put("password",bCryptPasswordEncoder.encode(paramMap.get("password").toString()));
        }
        storeFile(file, filePaths,request);
        paramMap.put("img",img);
        paramMap.put("crtDt",sdf.format(new Date()));
        userMapper.register(paramMap);
        return Result.ok("注册成功");
    }

    @Override
    public Result getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT tokenInfo = JWTUtil.getTokenInfo(token);
        String account = tokenInfo.getSubject();
        Map<String,Object> map=new HashMap<>();
        map.put("account",account);
        Map<String,Object> userInfo=userMapper.getUserInfo(map);
        return Result.ok(userInfo);
    }
    @Transactional
    @Override
    public Result upUserInfo(MultipartFile[] file, Map<String, Object> map, HttpServletRequest request) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> paramMap= (Map<String, Object>) JSONUtils.parse(map.get("paramMap").toString());
        //返回图片保存地址
        String img=null;
        if(file!=null&&file.length>0){
            img= file[0].getOriginalFilename();
            try {
                File file1 = new File(filePaths + "\\" + img);
                if(file1.exists()){
                    FileUtils.forceDelete(file1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            storeFile(file, filePaths,request);
            paramMap.put("img",img);
        }
        if(paramMap.get("password")!=null&&!paramMap.get("password").toString().equals("")){
            paramMap.put("password",bCryptPasswordEncoder.encode(paramMap.get("password").toString()));
        }
        userMapper.upUserInfo(paramMap);
        return Result.ok("修改成功");
    }

    @Override
    public Result getAllUser(Map<String, Object> params) {
        Integer pageIndex=Integer.parseInt(params.get("pageIndex").toString())-1;
        Integer pageSize=Integer.parseInt(params.get("pageSize").toString());
        params.put("pageIndex",pageIndex*pageSize);
        params.put("pageSize",pageSize);
        List<Map<String,Object>> result=userMapper.getAllUser(params);
        int count=userMapper.getUserCont();
        return Result.ok(result).setRecordsCount((long) count);
    }

    @Transactional
    @Override
    public Result deleteUser(Map<String, Object> params) {
        userMapper.deleteUser(params);
        return Result.OK_EMPTY;
    }

    @Override
    public Result getUserRole(Map<String, Object> params) {
        List<String> list=userMapper.getUserRole(params);
        return Result.ok(list);
    }

    @Transactional
    @Override
    public Result inserUserRole(Map<String, Object> paramMap, HttpServletRequest request) {
        //删除
        userMapper.deletUserRole(paramMap);
        //插入
        if(paramMap.get("roleId")!=null){
            List<String> list= (List<String>) paramMap.get("roleId");
            if(list.size()>0){
                userMapper.inserUserRole(paramMap);
            }

        }
        return Result.ok("配置角色成功");
    }

    //存储File
    public String storeFile(MultipartFile[] files, String path,HttpServletRequest request) {
        List<String> paths=new ArrayList<>();
        if(!Objects.isNull(files)){
            for (MultipartFile file:files) {
                // 获取原始文件名
                String fileName = file.getOriginalFilename();
                // // 获取文件后缀
                // String suffixName = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".")) : null;
                // //文件的保存重新按照时间戳命名
                // String newFileName = System.currentTimeMillis() + suffixName;
                // 最终保存的文件
                File filePath = new File(path + File.separator + fileName);
                // 判断文件夹是否存在
                if (!filePath.getParentFile().exists()) {
                    filePath.getParentFile().mkdirs();
                }
                // 保存文件
                try {
                    file.transferTo(filePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                paths.add(filePath.toString());
                // 如果成功，会返回文件的绝对路径，方便下载
            }
        }
        String uploadPath=null;
        if(paths.size()>0){
            uploadPath= String.join(",", paths);
        }
        return uploadPath;
    }
}
